package top.lvjp.designMode;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/** 抽象角色 */
interface Service{
    void save();
}

/** 真实角色 */
class RealService implements Service{
    @Override
    public void save() {
        System.out.println("----save----");
    }
}

/** 代理角色处理器 */
class ServiceHandler implements InvocationHandler{
    private Service realService;

    public ServiceHandler(Service realService) {
        this.realService = realService;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if(!"save".equals(method.getName())) return null;
        System.out.println("proxy: "+proxy.getClass());
        System.out.println("method:"+method);
        System.out.println("args: "+args);
        return method.invoke(realService,args);
    }
}
/** 测试动态代理 */
public class ProxyTest {
    public static void main(String[] args) {
        Service service = new RealService();
        ServiceHandler handler = new ServiceHandler(service);
        Service proxy = (Service)Proxy.newProxyInstance(Service.class.getClassLoader(),new Class[]{Service.class},handler);
        proxy.save();
    }
}
